package com.friend.campusnotice.util;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.friend.campusnotice.R;
import com.friend.campusnotice.bean.Contacts;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/24.
 */
public class MyUtil {

    /**
     * 获取库Phon表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};

    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;

    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;

    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;

    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;


    /**
     * 联系人名称
     **/
    private ArrayList<String> mContactsName = new ArrayList<String>();

    /**
     * 联系人h号码
     **/
    private ArrayList<String> mContactsNumber = new ArrayList<String>();

    /**
     * 联系人头像
     **/
    private ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>();

    /**
     * 联系人ID
     **/
    private ArrayList<Long> mContactsId = new ArrayList<Long>();

    /**
     * 联系人头像Id
     **/
    private ArrayList<Long> mContactsIconId = new ArrayList<Long>();

    private Map<String, Object> allData = new HashMap<String, Object>();


    /**
     * 得到手机通讯录联系人信息
     **/
    public Map<String, Object> getPhoneContacts(Context mContext) {
        ContentResolver resolver = mContext.getContentResolver();

        // 获取手机联系人
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);


        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                //得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                //当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;

                //得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);

                //得到联系人ID
                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);

                //得到联系人头像ID
                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);

                //得到联系人头像Bitamp
//                Bitmap contactPhoto = null;
//
//                //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
//                if(photoid > 0 ) {
//                    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);
//                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
//                    contactPhoto = BitmapFactory.decodeStream(input);
//                }else {
//                    contactPhoto = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.mengmeng);
//                }

                mContactsName.add(contactName);
                mContactsNumber.add(phoneNumber);
                mContactsId.add(contactid);
                mContactsIconId.add(photoid);
                //mContactsPhonto.add(contactPhoto);
            }

            phoneCursor.close();

            allData.put("ContactsName", mContactsName);
            allData.put("ContactsNumber", mContactsNumber);
            allData.put("ContactId", mContactsId);
            allData.put("ContactsIconId", mContactsIconId);
            //allData.put("ContactsPhonto",mContactsPhonto);
        }

        return allData;
    }

    public Boolean deleteContact(String number, Context mContext) {
        ContentResolver resolver = mContext.getContentResolver();
        // 获取手机联系人
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, "data1 = ?", new String[]{number}, null);
        if (phoneCursor.moveToFirst()) {
            Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
            resolver.delete(uri, "contact_id=?", new String[]{contactid + ""});
            uri = Uri.parse("content://com.android.contacts/data");
            resolver.delete(uri, "raw_contact_id=?", new String[]{contactid + ""});
            phoneCursor.close();
            return true;
        } else {

            phoneCursor.close();
            return false;
        }


    }


    public List<com.friend.campusnotice.bean.CallLog> getSingleCall(Context context, String number) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
                new String[]{CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,
                        CallLog.Calls.TYPE, CallLog.Calls.DATE}, "number=?", new String[]{number}, CallLog.Calls.DEFAULT_SORT_ORDER);
        if (!cursor.moveToFirst()) {
            Log.i("xiaohei", "目前没有通话记录");
            return null;
        }

        List<com.friend.campusnotice.bean.CallLog> callLogList = new ArrayList<com.friend.campusnotice.bean.CallLog>();
        Log.i("xiaohei", "查到了");
        do {

            int numIndex = cursor.getColumnIndex(CallLog.Calls.NUMBER);
            int typeIndex = cursor.getColumnIndex(CallLog.Calls.TYPE);
            int calldateIndex = cursor.getColumnIndex(CallLog.Calls.DATE);
            int nameIndex = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
            String phoneNum = null;
            Long callDate = cursor.getLong(calldateIndex);
            phoneNum = cursor.getString(numIndex);
            int CallTp = cursor.getInt(typeIndex);

            String name = cursor.getString(nameIndex);
            String callType = null;
            switch (CallTp) {
                case 1://拨入
                    callType = "呼入";
                    break;
                case 2://拨出
                    callType = "呼出";
                    break;
                case 3://未接
                    callType = "未接";
                    break;
                default:
                    break;

            }

            com.friend.campusnotice.bean.CallLog callLog = new com.friend.campusnotice.bean.CallLog();
            callLog.setCallDate(callDate);
            callLog.setCallType(callType);
            callLog.setName(name);
            callLog.setPhoneNum(phoneNum);
            callLog.setSingle(true);
            callLogList.add(callLog);

        }while (cursor.moveToNext());
        return callLogList;

    };



    public List<com.friend.campusnotice.bean.CallLog> GetCall(Context context)
    {

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
                new String[] {
                        CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,
                        CallLog.Calls.TYPE, CallLog.Calls.DATE }, null, null,  CallLog.Calls.DEFAULT_SORT_ORDER);
        if (!cursor.moveToFirst()) {
            Log.i("xiaohei", "目前没有通话记录");
            return null;
        }


        HashSet<String> set = new HashSet<String>();
        LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();


        List<com.friend.campusnotice.bean.CallLog> callLogList = new ArrayList<com.friend.campusnotice.bean.CallLog>();

        do {
            int numIndex = cursor.getColumnIndex(CallLog.Calls.NUMBER);
            int typeIndex = cursor.getColumnIndex(CallLog.Calls.TYPE);
            int calldateIndex = cursor.getColumnIndex(CallLog.Calls.DATE);
            int nameIndex = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
            String phoneNum = null;
            Long callDate = cursor.getLong(calldateIndex);
            phoneNum = cursor.getString(numIndex);
            int CallTp = cursor.getInt(typeIndex);
           // Integer count = map.get(phoneNum);
            if (set.add(phoneNum)) {

                String name = cursor.getString(nameIndex);
                String callType = null;
                switch (CallTp) {
                    case 1://拨入
                        callType = "呼入";
                        break;
                    case 2://拨出
                        callType = "呼出";
                        break;
                    case 3://未接
                        callType = "未接";
                        break;
                    default:
                        break;

                }

                com.friend.campusnotice.bean.CallLog callLog = new com.friend.campusnotice.bean.CallLog();
                callLog.setCallDate(callDate);
                callLog.setCallType(callType);
                callLog.setName(name);
                callLog.setPhoneNum(phoneNum);
                callLog.setSingle(false);
                callLogList.add(callLog);
            }

        } while (cursor.moveToNext());

        return callLogList;
    }


}
